using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Win32.Dialogs;
using System;
using System.Threading.Tasks;
using System.Linq;
using HtmlAgilityPack;

namespace Tests
{
	class Chrome
	{
		private readonly Browser browser;

		public Chrome(Browser browser)
		{
			this.browser = browser;
		}

		/// <summary>
		/// Returns <code>null</code> if no document was loaded,
		/// implying <param name="address"/> was probably interpreted as a file download.
		/// </summary>
		public async Task<HtmlDocument> NavigateTo(Uri address)
		{
			await NavigateToInternal(address);
			var loadedInBrowser = IsBeingViewed(address);
			if (!loadedInBrowser)
				return null;

			var htmlSource = new HtmlDocument();
			htmlSource.LoadHtml(browser.ViewSourceString);

			return htmlSource;
		}

		private Task NavigateToInternal(Uri address)
		{
			return Task.Run(() => browser.NavigateTo(address));
		}

		private bool IsBeingViewed(Uri address)
		{
			return address == CurrentAddress;
		}

		private Uri CurrentAddress
		{
			get
			{
				var hasAddress = browser.Url.Any();
				return hasAddress ? new Uri(browser.Url) : null;
			}
		}
	}
}
